class Solution:
    def stoneGameV(self, stoneValue: list) -> int:
        def func(stone, stoneSum, start, end, memo):
            if start == end:
                return 0
            if memo[start][end] > 0:
                return memo[start][end]
            ans = 0
            preSum = stone[start]
            for i in range(start + 1, end + 1):
                lastSum = stoneSum - preSum
                if preSum >= lastSum:
                    ans = max(lastSum + func(stone, lastSum, i, end, memo),
                              ans)
                if preSum <= lastSum:
                    ans = max(preSum + func(stone, preSum, start, i - 1, memo),
                              ans)
                preSum += stone[i]

            memo[start][end] = ans
            return ans

        return func(stoneValue, sum(stoneValue), 0,
                    len(stoneValue) - 1, [[0 for _ in range(len(stoneValue))]
                                          for _ in range(len(stoneValue))])
